<template>
  <div></div>
</template>

<script>
import * as d3 from "d3";
export default {
  name: "histogram",
  props: {
    width: {
      type: Number
    },
    height: {
      type: Number
    }
  },
  mounted() {
    const width = this.width, height = this.height;
    // 在body里添加一个SVG画布
    let svg = d3.select(this.$el)
      .append('svg')
      .attr('width', width)
      .attr('height', height)
    // 画布周边的空白
    const padding = { left: 30, right: 30, top: 20, bottom: 20 };
    // 定义一个数组
    let dataset = [10, 20, 30, 40, 33, 24, 12, 5];
    // x轴的比例尺---scaleBand()数字比例尺
    let xScale = d3
      .scaleBand()
      .domain(d3.range(dataset.length))
      .rangeRound([0, width - padding.left - padding.right]);
    // y轴的比例尺
    let yScale = d3
      .scaleLinear()
      .domain([0, d3.max(dataset)])
      .range([height - padding.top - padding.bottom, 0]);
    // 定义坐标轴
    // 定义x轴
    let xAxis = d3.axisBottom(xScale);
    let yAxis = d3.axisLeft(yScale);

    // 添加矩形和文字元素
    let rectPadding = 4; // 矩形之间的空白
    svg.selectAll("rect")
      .data(dataset)
      .enter()
      .append("rect")
      .attr("transform", `translate(${padding.left},${padding.top})`)
      .attr("x", function(d, i) {
        return xScale(i) + rectPadding / 2;
      })
      .attr("y", function(d) {
        return yScale(d);
      })
      .attr("width", xScale.bandwidth() - rectPadding)
      .attr("height", function(d) {
        return height - padding.top - padding.bottom - yScale(d);
      })
      .attr("fill", "steelblue");
    svg.selectAll("text")
      .data(dataset)
      .enter()
      .append("text")
      .attr("transform", `translate(${padding.left},${padding.top})`)
      .attr("x", function(d, i) {
        return xScale(i) + rectPadding / 2;
      })
      .attr("y", function(d) {
        return yScale(d);
      })
      .attr("dx", function() {
        return (xScale.bandwidth() - rectPadding) / 2;
      })
      .attr("dy", function() {
        return 20;
      })
      .text(function(d) {
        return d;
      })
      .attr("fill", "#ffffff");
    svg.append("g")
      .attr(
        "transform",
        `translate(${padding.left},${height - padding.bottom})`
      )
      .call(xAxis);
    svg.append("g")
      .attr("transform", `translate(${padding.left},${padding.top})`)
      .call(yAxis);
  }
};
</script>

<style scoped>
</style>

